//
//  LuaCanvas.cpp
//  Olivia
//
//  Created by 钟昆达 on 13-3-20.
//
//

#include "Canvas.h"
#include "camerabinding.h"
#include "lua.hpp"
#include "../../lua_ogre/luaclassbinding.h"
#include "OgreCamera.h"
#include "OgreViewport.h"

namespace Olivia {
    
LuaCanvas::LuaCanvas(Canvas *canvas) : c_obj(canvas)
{}
    
LuaCanvas::~LuaCanvas()
{
    if (NULL != c_obj)
    {
        c_obj->m_script_obj = NULL;
        delete c_obj;
        c_obj = NULL;
    }
}
    
const char* LuaCanvas::GetName() const
{
    return c_obj->GetName();
}

const char* LuaCanvas::GetClassName()
{
    return CanvasClassName;
}
    
static int GetCamera(Canvas *canvas, lua_State *ls)
{
    lua_pushlightuserdata(ls, canvas->GetScriptObject()->lua_cam);
    return 1;
}
    
static int GetBackGroundColor(Canvas *canvas, lua_State *ls)
{
    char value[20];
    sprintf(value, "0x%x", canvas->GetCamera()->getViewport()->getBackgroundColour().getAsARGB());
    lua_pushstring(ls, value);
    return 1;
}
    
static int SetBackGroundColor(Canvas *canvas, lua_State *ls)
{
    if (lua_gettop(ls) != 1 || !lua_isnumber(ls, 1))
    {
        printf("set Scene.ambient error, invalid value!");
        return 0;
    }
    
    Ogre::ColourValue color;
    color.setAsARGB(Ogre::uint32(lua_tonumber(ls, 1)));
    canvas->GetCamera()->getViewport()->setBackgroundColour(color);
    return 0;
}
    
static LuaMethod<Canvas> g_canvas_methods_and_props[] = {
    {"getcamera", GetCamera, 0, 0},
    {"backgroundcolor", 0, GetBackGroundColor, SetBackGroundColor},
    {0, 0}
};
    
static int CanvasAlloc(lua_State *ls)
{
    lua_remove(ls, 1);
    Canvas *can = new Canvas;
    if (0 == can)
    {
        return 0;
    }
    
    LuaCanvas *mem = (LuaCanvas*)lua_newuserdata(ls, sizeof(LuaCanvas));
    if (0 == mem)
    {
        delete can;
        return 0;
    }
    
    if (lua_gettop(ls) == 1
        && lua_isstring(ls, 1))
    {
        can->SetName(lua_tostring(ls, 1));
    }
    
    new(mem) LuaCanvas(can);
    luaL_getmetatable(ls, CanvasClassName);
    lua_setmetatable(ls, -2);
    
    mem->lua_cam = lua_ogre::CreateLuaCamera(can->GetCamera(), ls);
    return 1;
}
    
bool BindCanvas(lua_State *ls)
{
    typedef LuaClassBind<Canvas, LuaCanvas> CanvasBind;
    
    LuaTypeObject<Canvas> type_obj(
        CanvasClassName,
        g_canvas_methods_and_props,
        CanvasAlloc,
        CanvasBind::Dealloc,
        CanvasBind::ToString,
        CanvasBind::Thunk);
    
    return CanvasBind::Register(ls, type_obj);
}
    
}
